<template>
  <div class="login-log h-full">
    <div class="login-log-nav flex">
      <div
        @click="curIndex = index"
        :class="curIndex === index ? 'active' : ''"
        v-for="(item, index) in navList"
        :key="index"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="login-log-content">
      <div class="form-search">
        <div class="right">
          <a-tree-select
            class="ml-5"
            placeholder="全部组织机构"
            allow-clear
            tree-default-expand-all
            :tree-data="treeData"
            v-model:value="searchForm.deptId"
            :field-names="{
              children: 'children',
              label: 'name',
              value: 'id'
            }"
          >
            <template #title="{ label }">
              <div :title="label" class="ellipsis-label">
                {{ label }}
              </div>
            </template>
          </a-tree-select>
          <a-select
            class="ml-5"
            v-model:value="searchForm.status"
            allow-clear
            placeholder="全部操作结果"
            :options="statusList"
          ></a-select>
          <a-range-picker
            class="ml-5"
            :value="hackDatesValue || dateRange"
            :separator="'至'"
            format="YYYY-MM-DD"
            @calendarChange="onCalendarChange"
            @openChange="onOpenChange"
            @change="onRangeChange"
            :disabledDate="disabledDate"
          ></a-range-picker>
          <a-input
            v-model:value.trim="searchForm.nickName"
            placeholder="请输入用户姓名"
            v-filter-special-chars
            class="search-input-w"
          ></a-input>
          <search-button
            @search="getList(true, true)"
            @refresh="getList(true, true)"
            @reset="reset()"
          ></search-button>
        </div>
      </div>
      <div class="common-table">
        <a-table
          :dataSource="dataSource"
          :columns="columns"
          :pagination="false"
          :loading="loading"
        >
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex === 'order'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>
            <template v-else-if="column.dataIndex === 'status'">
              <div
                :style="{
                  background: record.status === '0' ? '#53D229' : '#FF6F62'
                }"
                class="status-item"
              >
                {{ record.status === '0' ? '成功' : '失败' }}
              </div>
            </template>
          </template>
        </a-table>
      </div>
      <div class="common-pagination">
        <Pagination @getListByPage="getListByPage" ref="paginationRef" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { loadList } from '@/api/loginLog'
import SearchButton from '@/components/SearchButton.vue'
import { getOrgTree } from '@/api/organization'
import dayjs, { Dayjs } from 'dayjs'
const treeData = ref<any[]>([])
const dataSource = ref()
const loading = ref<boolean>(false)
const paginationRef = ref()
const statusList = ref([
  {
    label: '成功',
    value: 0
  },
  {
    label: '失败',
    value: 1
  }
])
const dateRange = ref<Dayjs[]>([dayjs().subtract(1, 'month'), dayjs()])
const dates = ref<Dayjs[]>([])
const hackDatesValue = ref<Dayjs[]>()
const curIndex = ref(0)
const navList = [
  {
    name: '登录日志'
  }
]
let searchFormClone = {
  deptId: null,
  userName: '',
  status: null,
  startDate: '',
  endDate: '',
  pageNum: 1,
  pageSize: 10,
  nickName: ''
}
const searchForm = reactive({
  userName: '',
  deptId: null,
  status: null,
  startDate: '',
  endDate: '',
  nickName: ''
})
const columns = ref([
  {
    title: '序号',
    dataIndex: 'order',
    width: '7.5rem'
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true
  },
  {
    title: '姓名',
    dataIndex: 'nickName',
    key: 'nickName',
    ellipsis: true
  },
  {
    title: '组织机构',
    dataIndex: 'deptName',
    key: 'deptName',
    ellipsis: true
  },
  {
    title: 'IP地址',
    dataIndex: 'ipaddr',
    key: 'ipaddr',
    ellipsis: true
  },
  {
    title: '操作结果',
    dataIndex: 'status',
    key: 'status',
    ellipsis: true
    // width: 120
  },
  {
    title: '详情',
    dataIndex: 'msg',
    key: 'msg',
    ellipsis: true
  },
  {
    title: '操作时间',
    dataIndex: 'accessTime',
    key: 'accessTime',
    ellipsis: true,
    width: '12.25rem'
  }
])
const disabledDate = (current: Dayjs) => {
  const currentFormat = dayjs(current).format('YYYY-MM-DD')
  const currentDate = dayjs().format('YYYY-MM-DD')
  if (currentDate < currentFormat) return true
  if (!dates.value || (!dates.value[0] && !dates.value[1])) {
    return false
  }
  if (dates.value[0] && current > dayjs(dates.value[0]).add(1, 'year'))
    return true
  if (dates.value[1] && current < dayjs(dates.value[1]).subtract(1, 'year'))
    return true
  return false
}
const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any
    hackDatesValue.value = [] as any
  } else {
    hackDatesValue.value = undefined
  }
}
const onCalendarChange = (val: Dayjs[]) => {
  dates.value = val
}
const onRangeChange = (val: Dayjs[]) => {
  dateRange.value = val
}
const getDeptTree = () => {
  getOrgTree().then((res) => {
    if (!res) return
    treeData.value = res
  })
}
const reset = () => {
  searchForm.userName = ''
  searchForm.nickName = ''
  searchForm.deptId = null
  searchForm.status = null
  dateRange.value = [dayjs().subtract(1, 'month'), dayjs()]
}
const pagination = reactive({
  total: 0,
  pageSize: 10, // 每页中显示10条数据
  position: ['bottomCenter'],
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})
// 日期选择处理
const setTime = () => {
  if (dateRange.value?.length) {
    return {
      startDate: dayjs(dateRange.value[0]).format('YYYY-MM-DD'),
      endDate: dayjs(dateRange.value[1]).format('YYYY-MM-DD')
    }
  } else {
    return {
      startDate: '',
      endDate: ''
    }
  }
}
const getList = (flag = false, isSearch = false) => {
  if (flag) {
    pagination.current = 1
    paginationRef.value.changeCurrent(pagination.current)
  }
  loading.value = true
  dataSource.value = []
  const { startDate, endDate } = setTime()
  const params = {
    deptId: searchForm.deptId,
    nickName: searchForm.nickName,
    status: searchForm.status,
    startDate,
    endDate,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  if (isSearch) {
    searchFormClone = JSON.parse(JSON.stringify(params))
  } else {
    params.deptId = searchFormClone.deptId
    params.nickName = searchFormClone.nickName
    params.status = searchFormClone.status
    params.startDate = searchFormClone.startDate
    params.endDate = searchFormClone.endDate
  }
  loadList(params)
    .then((res) => {
      if (res) {
        dataSource.value = res.list
        pagination.total = res.total
        paginationRef.value.changeTotal(pagination.total)
        loading.value = false
      } else {
        loading.value = false
      }
    })
    .catch(() => {
      loading.value = false
    })
}
const getListByPage = (page: number, pageSize: number) => {
  if (pagination.current !== page) {
    pagination.current = page
    getList()
  }
  if (pagination.pageSize !== pageSize) {
    pagination.pageSize = pageSize
    getList(true)
  }
}
onMounted(() => {
  getDeptTree()
  getList(true, true)
})
</script>
<style lang="less" scoped>
/* stylelint-disable-next-line string-quotes */
.login-log {
  overflow-x: hidden;
  overflow-y: auto;
  height: 100%;

  &-nav {
    height: 2.25rem;
    line-height: 2.25rem;
    border-bottom: 1px solid #f0f0f0;

    > div {
      height: 2.25rem;
      font-size: 1rem;
      color: #707479;
      line-height: 1.25rem;
      font-weight: 400;
      cursor: pointer;
    }

    > div + div {
      margin-left: 1.875rem;
    }

    .active {
      color: @primary-color;
      font-weight: bold;
      border-bottom: 2px solid @primary-color;
    }
  }

  &-content {
    padding-top: 1.25rem;
    height: calc(100% - 2.25rem);
  }

  .form-search {
    justify-content: flex-end;
  }

  .common-table {
    overflow-y: auto;
    height: calc(100% - 7.3rem);

    .status-item {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 5.5rem;
      height: 100%;
      color: @bg-color;
      border-radius: 0.25rem;
    }
  }

  .common-pagination {
    margin-top: 0.8rem;
    height: 2rem;
  }

  .ml-5 {
    margin-right: 1.25rem;
  }
}
</style>
